package com.fishingwithme.android.ui.screens.circle

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.CirclePageDto
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.CircleViewModel

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun CircleScreen(
    navController: NavController,
    viewModel: CircleViewModel = hiltViewModel()
) {
    var searchTitle by remember { mutableStateOf("") }
    var selectedCityCode by remember { mutableStateOf<String?>(null) }
    var selectedCityName by remember { mutableStateOf<String?>("选择城市") }
    var isActive by remember { mutableStateOf(true) } // Default to active circles
    var showCitySelector by remember { mutableStateOf(false) }
    var citySearchQuery by remember { mutableStateOf("") }
    var citySearchResults by remember { mutableStateOf<List<City>>(emptyList()) }
    var isSearchingCities by remember { mutableStateOf(false) }
    var previousCitySearchQuery by remember { mutableStateOf("") }
    var hasInitiallySearched by remember { mutableStateOf(false) }

    val circles =
        viewModel.getCircles(searchTitle, selectedCityCode, isActive).collectAsLazyPagingItems()

    // Trigger city search when query changes (with debounce)
    androidx.compose.runtime.LaunchedEffect(citySearchQuery) {
        if (previousCitySearchQuery != citySearchQuery) {
            previousCitySearchQuery = citySearchQuery
            // Debounce search to avoid too many API calls
            kotlinx.coroutines.delay(300)
            // Check if the query is still the same after delay
            if (citySearchQuery == previousCitySearchQuery) {
                isSearchingCities = true
                viewModel.searchCities(citySearchQuery) { cities ->
                    citySearchResults = cities
                    isSearchingCities = false
                }
            }
        }
    }

    // Trigger initial city search when city selector is opened
    androidx.compose.runtime.LaunchedEffect(showCitySelector) {
        if (showCitySelector && !hasInitiallySearched) {
            hasInitiallySearched = true
            isSearchingCities = true
            // Immediately query cities when opened (as per user preference)
            viewModel.searchCities("") { cities ->
                citySearchResults = cities
                isSearchingCities = false
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.surface)
    ) {
        // Search Criteria Section
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_16),
            elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(AppDimensions.SPACING_16)
            ) {
                // Title search input
                TextField(
                    value = searchTitle,
                    onValueChange = { searchTitle = it },
                    label = { Text("搜索标题") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_12),
                    singleLine = true
                )

                // City selector and active filter row
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = AppDimensions.SPACING_8),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // City selector button
                    Button(
                        onClick = {
                            showCitySelector = true
                            // Reset search query when opening selector
                            citySearchQuery = ""
                        },
                        modifier = Modifier
                            .weight(2f)
                            .padding(end = AppDimensions.SPACING_8)
                    ) {
                        Text(selectedCityName ?: "选择城市")
                    }

                    // Active filter switch with label
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .weight(1f)
                            .padding(start = AppDimensions.SPACING_8)
                    ) {
                        Text(
                            text = "活跃",
                            style = MaterialTheme.typography.bodyMedium
                        )
                        Spacer(modifier = Modifier.width(AppDimensions.SPACING_8))
                        Switch(
                            checked = isActive,
                            onCheckedChange = { isActive = it }
                        )
                    }
                }

                // Add Button
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = AppDimensions.SPACING_12),
                    horizontalArrangement = Arrangement.End
                ) {
                    Button(
                        onClick = {
                            navController.navigate(FishingNavigation.ADD_CIRCLE)
                        },
                        modifier = Modifier
                    ) {
                        Icon(
                            imageVector = Icons.Default.Add,
                            contentDescription = stringResource(R.string.add_circle),
                            modifier = Modifier.size(AppDimensions.ICON_SIZE_16)
                        )
                        Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
                        Text(stringResource(R.string.add_circle))
                    }
                }
            }
        }

        // City selector dialog (using proper bottom sheet with search)
        if (showCitySelector) {
            val sheetState = rememberModalBottomSheetState()
            ModalBottomSheet(
                onDismissRequest = {
                    showCitySelector = false
                    // Reset state when closing
                    hasInitiallySearched = false
                },
                sheetState = sheetState
            ) {
                CitySelectorContent(
                    searchQuery = citySearchQuery,
                    onSearchQueryChange = { query ->
                        citySearchQuery = query
                    },
                    filteredCities = citySearchResults,
                    isSearching = isSearchingCities,
                    onCitySelected = { city ->
                        selectedCityCode = city.cityCode
                        selectedCityName = city.city
                        showCitySelector = false
                        // Reset search query and results when a city is selected
                        citySearchQuery = ""
                        citySearchResults = emptyList()
                        hasInitiallySearched = false
                    }
                )
            }
        }

        // Circles grid
        LazyVerticalGrid(
            columns = GridCells.Fixed(3),
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = AppDimensions.SPACING_8),
            verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8),
            horizontalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8)
        ) {
            items(circles.itemCount) { index ->
                circles[index]?.let { circle ->
                    CircleItem(circle = circle, navController)
                }
            }

            // Handle loading states
            when {
                circles.loadState.refresh is LoadState.Loading -> {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = AppDimensions.SPACING_32),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                }

                circles.loadState.append is LoadState.Loading -> {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = AppDimensions.SPACING_16),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                }

                circles.loadState.refresh is LoadState.Error -> {
                    val error = (circles.loadState.refresh as LoadState.Error).error
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = AppDimensions.SPACING_32),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "加载失败: ${error.message}",
                                color = MaterialTheme.colorScheme.error
                            )
                        }
                    }
                }

                circles.itemCount == 0 && circles.loadState.refresh is LoadState.NotLoading -> {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = AppDimensions.SPACING_32),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "暂无数据",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CitySelectorContent(
    searchQuery: String,
    onSearchQueryChange: (String) -> Unit,
    filteredCities: List<City>,
    isSearching: Boolean,
    onCitySelected: (City) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(AppDimensions.SPACING_16)
    ) {
        // Search input
        TextField(
            value = searchQuery,
            onValueChange = onSearchQueryChange,
            label = { Text("搜索城市") },
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = "Search"
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_16),
            colors = TextFieldDefaults.textFieldColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            )
        )

        // City list
        LazyColumn {
            // Show loading indicator when searching
            if (isSearching) {
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppDimensions.SPACING_16),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
            } else {
                items(filteredCities) { city ->
                    CityItem(
                        city = city,
                        onClick = { onCitySelected(city) }
                    )
                }

                // Show a message when search returns no results
                if (filteredCities.isEmpty() && searchQuery.isNotEmpty()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_16),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "未找到相关城市",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CityItem(
    city: City,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = AppDimensions.SPACING_2),
        onClick = onClick,
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        )
    ) {
        Text(
            text = city.city ?: "未知城市",
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_16)
        )
    }
}

@Composable
private fun CircleItem(
    circle: CirclePageDto,
    navController: NavController
) {
    var imageLoadError by remember { mutableStateOf(false) }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable {
                val router = "${FishingNavigation.CIRCLE_MGR}?id=${circle.id}"
                navController.navigate(router)
            },
        shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8),
        elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(120.dp)

        ) {
            // Background image (first picture)
            if (circle.pics.isNotEmpty() && !imageLoadError) {
                val painter = rememberAsyncImagePainter(
                    ImageRequest.Builder(LocalContext.current)
                        .data(circle.pics.firstOrNull())
                        .crossfade(true)
                        .build()
                )
                Image(
                    painter = painter,
                    contentDescription = null,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            } else {
                // Placeholder if no image or image load failed
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.surfaceVariant),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无图片",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }
            }

            // Overlay with semi-transparent background for text readability
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(AppDimensions.SPACING_8),
                verticalArrangement = Arrangement.Bottom
            ) {
                // Dark overlay for better text visibility
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(AppDimensions.SPACING_2)
                        .background(Color.Black.copy(alpha = 0.5f))
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppDimensions.SPACING_4)
                    ) {
                        Text(
                            text = circle.title,
                            style = MaterialTheme.typography.bodyMedium,
                            color = Color.White,
                            fontWeight = FontWeight.Bold,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                        Text(
                            text = circle.city,
                            style = MaterialTheme.typography.bodySmall,
                            color = Color.White,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }

            // Active status indicator
            if (circle.isActive == 1) {
                Box(
                    modifier = Modifier
                        .padding(AppDimensions.SPACING_4)
                        .align(Alignment.TopEnd)
                        .background(
                            color = MaterialTheme.colorScheme.primary,
                            shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_50)
                        )
                        .padding(
                            horizontal = AppDimensions.SPACING_4,
                            vertical = AppDimensions.SPACING_2
                        )
                ) {
                    Text(
                        text = "活跃",
                        style = MaterialTheme.typography.labelSmall,
                        color = Color.White
                    )
                }
            }
        }
    }
}